/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved.
 * Description: Hmfs-tools sit
 */

#include "compare_sit.h"

#include <memory>
#include <cinttypes>
#include <cmath>
#include <string>
#include <sys/types.h>

#include "hmfs_log.h"
#include "hmfs_utils.h"
#include "io.h"
#include "securec.h"

namespace OHOS {
namespace Hmfs {
int32_t CompareSit::CompareSitArea()
{
    if (ReadSitArea(srcInfo_)) {
        HMFS_ERROR("Failed to read sit area.");
        return -1;
    }
    if (ReadSitArea(dstInfo_)) {
        HMFS_ERROR("Failed to read sit area.");
        return -1;
    }

    uint64_t sitBufferSize = (GetLeValue(srcInfo_.superBlock->segmentCountInSIT) <<
        GetLeValue(srcInfo_.superBlock->logBlksPerSeg)) * HMFS_BLOCK_SIZE;
    if (memcmp(srcInfo_.sitBuf.get(), dstInfo_.sitBuf.get(), sitBufferSize)) {
        HMFS_ERROR("sit not equal, at offset 0x%" PRIx64 ", len = 0x%" PRIx64 "", srcInfo_.sitOffset, sitBufferSize);
    }

    return 0;
}

int32_t CompareSit::ReadSitArea(FsData &fsInfo)
{
    fsInfo.sitOffset = GetLeValue(fsInfo.superBlock->sitBlockId) * HMFS_BLOCK_SIZE;
    HMFS_INFO("sitOffset = 0x%" PRIx64 ".", fsInfo.sitOffset);

    uint64_t sitBufferSize = (GetLeValue(fsInfo.superBlock->segmentCountInSIT) <<
        GetLeValue(fsInfo.superBlock->logBlksPerSeg)) * HMFS_BLOCK_SIZE;
    fsInfo.sitBuf = std::make_unique<char[]>(sitBufferSize);
    if (DevRead(fsInfo, fsInfo.sitBuf.get(), fsInfo.sitOffset, sitBufferSize)) {
        HMFS_ERROR("Failed to read sit area.");
        return -1;
    }

    return 0;
}
} // namespace Hmfs
} // namespace OHOS
